package com.yunti.yntk.activity.updateScore;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSONObject;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.textfield.TextInputEditText;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.yunti.yntk.MyApplication;
import com.yunti.yntk.R;
import com.yunti.yntk.activity.BaseActivity;
import com.yunti.yntk.anotation.ViewInject;
import com.yunti.yntk.api.Result;
import com.yunti.yntk.db.AppDatabase;
import com.yunti.yntk.db.LocalRecordDao;
import com.yunti.yntk.db.po.ExamStu;
import com.yunti.yntk.db.po.LocalRecord;
import com.yunti.yntk.manager.ComputScoreManager;
import com.yunti.yntk.manager.ConfigManager;
import com.yunti.yntk.manager.NetWorkManager;
import com.yunti.yntk.manager.TTSManager;
import com.yunti.yntk.manager.TotalStationManager;
import com.yunti.yntk.model.FieldShowRes;
import com.yunti.yntk.model.PointPosition;
import com.yunti.yntk.service.WebServer;
import com.yunti.yntk.util.BitmapUtils;
import com.yunti.yntk.util.NumberUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UpdateScoreZxActivity extends BaseActivity {

    @ViewInject(R.id.stuListView)
    private ListView checkStuListView;

    @ViewInject(R.id.stuName)
    private TextView stuName;

    @ViewInject(R.id.stuKsh)
    private TextView stuKsh;

    @ViewInject(R.id.groupId)
    private TextView groupIdText;

    @ViewInject(R.id.groupXh)
    private TextView groupXhText;

    @ViewInject(R.id.surveyResult)
    private TextView surveyResult;

    @ViewInject(R.id.stuResult)
    private TextView stuResult;

    @ViewInject(R.id.startSurvey)
    private TextView startSurvey;

    @ViewInject(R.id.confirmScore)
    private TextView confirmScore;

    @ViewInject(R.id.countRadioGroup)
    private RadioGroup countRadioGroup;

    @ViewInject(R.id.stuInfoLayout)
    private FlexboxLayout stuInfoLayout;

    @ViewInject(R.id.noStuContent)
    private LinearLayoutCompat noStuContent;


    @ViewInject(R.id.stuImage)
    private ImageView stuImage;

    @ViewInject(R.id.weiGui)
    private TextView weiGui;

    @ViewInject(R.id.queKao)
    private TextView queKao;

    @ViewInject(R.id.shangTui)
    private TextView shangTui;

    @ViewInject(R.id.mianKao)
    private TextView mianKao;

    @ViewInject(R.id.finish)
    Button finish;

    @ViewInject(R.id.nextButton)
    Button nextButton;

    @ViewInject(R.id.nextCountButton)
    Button nextCountButton;
    @ViewInject(R.id.uplight)
    Switch uplight;

    @ViewInject(R.id.downlight)
    Switch downlight;

    @ViewInject(R.id.autoReady)
    Switch autoReady;

    @ViewInject(R.id.constant)
    TextInputEditText constant;

    private double constantValue = 0;

    @ViewInject(R.id.edmSpanner)
    Spinner edmSpanner;

    @ViewInject(R.id.historyLayout)
    ConstraintLayout historyLayout;

    @ViewInject(R.id.historyListView)
    ListView historyListView;

    @ViewInject(R.id.cancelHistory_button)
    TextView cancelHistoryButton;

    private String subName;
    private Integer subId;
    private int groupId;

    private int nowCount = 1;

    private String batch;

    private Integer sex;
    private List<ExamStu> examStuBeanArrayList = new ArrayList<>();
    private CheckStuItemAdapter checkStuItemAdapter;

    private ExamStu mExamStu;

    Double preScore;

    Map<String, Bitmap> bitmapMap = new HashMap<>();

    private LocalRecordDao localRecordDao;

    List<LocalRecord> examMarkLogList = new ArrayList<>();
    private RecordAdapter recordAdapter;

    WebServer webServer;

    @Override
    public int initLayoutId() {
        return R.layout.activity_updatescorezx;
    }

    @Override
    public void initView() {
        MyApplication app = (MyApplication) getApplication();
        webServer = app.getWebServer();
        recordAdapter = new RecordAdapter(getBaseContext(), R.layout.item_localrecord, examMarkLogList);
        historyListView.setAdapter(recordAdapter);

        edmSpanner.setSelection((int) TotalStationManager.getInstance().edm);
        edmSpanner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TotalStationManager.getInstance().setEdm(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        checkStuItemAdapter = new CheckStuItemAdapter(this, R.layout.item_update_stulist, examStuBeanArrayList);
        checkStuListView.setAdapter(checkStuItemAdapter);
        startSurvey.setOnClickListener(this::startSurvey);
        confirmScore.setOnClickListener(this::confirmScore);
        countRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // checkedId是当前选中的RadioButton的ID
                int index = countRadioGroup.indexOfChild(countRadioGroup.findViewById(checkedId));
                nowCount = index + 1;
                showStuInfo();
                // 使用index作为当前选中的RadioButton的索引
            }
        });
        finish.setOnClickListener(this::finish);
        weiGui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preScore = -1d;
                runOnUiThread(() -> {
                    surveyResult.setText("违例");
                });
            }
        });
        queKao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preScore = -2d;
                runOnUiThread(() -> {
                    surveyResult.setText("缺考");
                });
            }
        });
        shangTui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preScore = -3d;
                runOnUiThread(() -> {
                    surveyResult.setText("伤退");
                });
            }
        });
        mianKao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preScore = -4d;
                runOnUiThread(() -> {
                    surveyResult.setText("免考");
                });
            }
        });

        uplight.setChecked(TotalStationManager.getInstance().openLASER_POINTER);
        uplight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                TotalStationManager.getInstance().changeLASER_POINTER(isChecked);
            }
        });

        downlight.setChecked(TotalStationManager.getInstance().openLASER_PLUMMET);
        downlight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                TotalStationManager.getInstance().changeLASER_PLUMMET(isChecked);
            }
        });

        if (ConfigManager.getInstance().getAutoReady()) {
            autoReady.setChecked(true);
        } else {
            autoReady.setChecked(false);
        }

        autoReady.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ConfigManager.getInstance().setAutoReady(isChecked);
            }
        });

        constant.setText(ComputScoreManager.getInstance().getConstant() + "");
        constant.addTextChangedListener(new TextWatcher() {
            //编辑框的内容发生改变之前的回调方法
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            //编辑框的内容正在发生改变时的回调方法 >>用户正在输入
            //我们可以在这里实时地 通过搜索匹配用户的输入
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            //编辑框的内容改变以后,用户没有继续输入时 的回调方法
            @Override
            public void afterTextChanged(Editable s) {
                String aswer = s.toString();
                try {
                    ComputScoreManager.getInstance().setConstant(Double.parseDouble(aswer));
                    constantValue = Double.parseDouble(aswer);
                } catch (RuntimeException exception) {
                    exception.printStackTrace();
                    ComputScoreManager.getInstance().setConstant(0);
                }
            }
        });

        constantValue = ComputScoreManager.getInstance().getConstant();

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextStu();
            }
        });
        nextCountButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextCount();
            }
        });

        cancelHistoryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                historyLayout.setVisibility(View.GONE);
                examMarkLogList.clear();
                runOnUiThread(() -> {
                    recordAdapter.notifyDataSetChanged();
                });
            }
        });
        surveyResult.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                historyLayout.setVisibility(View.VISIBLE);
                getHistoryScore(1);
                return false;
            }
        });
        stuResult.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                historyLayout.setVisibility(View.VISIBLE);
                getHistoryScore(2);
                return false;
            }
        });
    }


    private void getHistoryScore(int type) {
        new Thread(() -> {
            List<LocalRecord> localRecordList = new ArrayList<>();
            if (type == 1) {
                localRecordList = localRecordDao.getHistoryList("测量");
            }
            if (type == 2) {
                localRecordList = localRecordDao.getHistoryList("提交", mExamStu.getStuName(), nowCount);
            }
            examMarkLogList.clear();
            if (localRecordList != null && localRecordList.size() > 0) {
                examMarkLogList.addAll(localRecordList);

            }
            runOnUiThread(() -> {
                recordAdapter.notifyDataSetChanged();
            });
        }).start();

    }

    private void nextStu() {
        if (NowIndex < examStuBeanArrayList.size() - 1) {
            mExamStu = examStuBeanArrayList.get(NowIndex + 1);
            showStuInfo();
            RadioButton defaultRadioButton = findViewById(R.id.rb_1);
            defaultRadioButton.setChecked(true);
        }


    }

    private void nextCount() {
        if (nowCount == 1) {
            RadioButton defaultRadioButton = findViewById(R.id.rb_2);
            defaultRadioButton.setChecked(true);
        } else if (nowCount == 2) {
            RadioButton defaultRadioButton = findViewById(R.id.rb_3);
            defaultRadioButton.setChecked(true);
        }
    }

    private void finish(View view) {
        finish();
    }


    private void startSurvey(View view) {
        QMUITipDialog tipDialog = new QMUITipDialog.Builder(this).setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING).setTipWord("测量中").create();
        tipDialog.show();
        new Thread(() -> {
            PointPosition pointPosition = TotalStationManager.getInstance().getPoint();
            if (!pointPosition.isTrue()) {
                runOnUiThread(() -> {
                    QMUITipDialog tipDialog2 = new QMUITipDialog.Builder(UpdateScoreZxActivity.this).setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL).setTipWord("测距失败!").create();
                    tipDialog2.show();
                    tipDialog.dismiss();
                    startSurvey.postDelayed(() -> {
                        tipDialog2.dismiss();
                    }, 500);
                });

            } else {
                double result = ComputScoreManager.getInstance().getScore(pointPosition);
                preScore = result;

                LocalRecord localRecord = new LocalRecord();
                localRecord.setArrangeId(mExamStu.getId());
                localRecord.setName(mExamStu.getStuName());
                localRecord.setXmmc("测量");
                localRecord.setZxmc(subName);
                Calendar calendar = Calendar.getInstance();
                Date now = calendar.getTime();
                localRecord.setDateField(now);
//        localRecord.setZxdm(mExamStu.getSubCode());
//        localRecord.setXmmc(selectExamSpecialArrange.getXmmc());
//        localRecord.setXmdm(selectExamSpecialArrange.getXmdm());
                localRecord.setCount(nowCount);
                localRecord.setScore(String.valueOf(preScore));
                localRecordDao.insertAll(localRecord);
                runOnUiThread(() -> {
                    surveyResult.setText(result + "米");
                    tipDialog.dismiss();
                });
                System.out.println(pointPosition);
            }

        }).start();
    }

    @Override
    public void initData() throws IOException {
        Intent intent = getIntent();
        subName = intent.getStringExtra("subName");
        subId = intent.getIntExtra("subId", 0);
        groupId = intent.getIntExtra("groupId", -1);
        batch = intent.getStringExtra("batch");
        sex = intent.getIntExtra("sex", 0);
        localRecordDao = AppDatabase.getDatabase(getBaseContext()).localRecordDao();
        getStuList();
    }

    private void getStuList() {

        JSONObject req = new JSONObject();

        req.put("subId", subId);
        req.put("groupId", groupId);
        req.put("batch", batch);
        req.put("sex", sex);
        Call<Result<List<ExamStu>>> call = NetWorkManager.getRequest().getBatchRecords(req);
        call.enqueue(new Callback<Result<List<ExamStu>>>() {
            @Override
            public void onResponse(Call<Result<List<ExamStu>>> call, Response<Result<List<ExamStu>>> response) {
                Result<List<ExamStu>> result = response.body();
                examStuBeanArrayList.clear();
                if (result.getData() != null && result.getData().size() != 0) {
                    examStuBeanArrayList.addAll(result.getData());
                }
                runOnUiThread(() -> {
                    checkStuItemAdapter.notifyDataSetChanged();
                });
            }

            @Override
            public void onFailure(Call<Result<List<ExamStu>>> call, Throwable t) {
                runOnUiThread(() -> {
                    checkStuItemAdapter.notifyDataSetChanged();
                });
            }
        });

    }

    private void confirmScore(View view) {
        if (mExamStu == null) {
            Toast.makeText(getBaseContext(), "请选择考生", Toast.LENGTH_SHORT);
            return;
        }
        if (preScore == null) {
            Toast.makeText(getBaseContext(), "请先测量成绩", Toast.LENGTH_SHORT);
            return;
        }
        boolean hasScore = false;
        if (nowCount == 1) {
            if (subId == 2) {
                if (mExamStu.getJumpScore1() != null) {
                    hasScore = true;
                }
            } else if (subId == 3) {
                if (mExamStu.getShotScore1() != null) {
                    hasScore = true;
                }
            } else {
                if (mExamStu.getSpecialScore1() != null) {
                    hasScore = true;
                }
            }
        } else if (nowCount == 2) {
            if (subId == 2) {
                if (mExamStu.getJumpScore2() != null) {
                    hasScore = true;
                }
            } else if (subId == 3) {
                if (mExamStu.getShotScore2() != null) {
                    hasScore = true;
                }
            } else {
                if (mExamStu.getSpecialScore2() != null) {
                    hasScore = true;
                }
            }
        } else if (nowCount == 3) {
            if (subId == 2) {
                if (mExamStu.getJumpScore3() != null) {
                    hasScore = true;
                }
            } else if (subId == 3) {
                if (mExamStu.getShotScore3() != null) {
                    hasScore = true;
                }
            } else {
                if (mExamStu.getSpecialScore3() != null) {
                    hasScore = true;
                }
            }
        }

        if (hasScore) {
            AlertDialog.Builder builder = new AlertDialog.Builder(UpdateScoreZxActivity.this);
            builder.setTitle("确认");
            builder.setMessage("检测到已有成绩，是否覆盖？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    updateScore();
                }
            });
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            builder.show();
        } else {
            updateScore();
        }


    }

    public void updateScore() {
        QMUITipDialog tipDialog = new QMUITipDialog.Builder(this).setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING).setTipWord("提交中").create();
        tipDialog.show();


        LocalRecord localRecord = new LocalRecord();
        localRecord.setArrangeId(mExamStu.getId());
        localRecord.setName(mExamStu.getStuName());
        localRecord.setXmmc("提交");
        localRecord.setZxmc(subName);
//        localRecord.setZxdm(mExamStu.getSubCode());
//        localRecord.setXmmc(selectExamSpecialArrange.getXmmc());
//        localRecord.setXmdm(selectExamSpecialArrange.getXmdm());
        localRecord.setCount(nowCount);
        localRecord.setScore(String.valueOf(preScore));
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        localRecord.setDateField(now);
        new Thread(() -> {
            localRecordDao.insertAll(localRecord);
        }).start();

        JSONObject req = new JSONObject();
        req.put("subId", subId);
        req.put("id", mExamStu.getId());

        req.put("count", nowCount);
        if (preScore == -1) {

        } else if (preScore == -2) {

        } else if (preScore == -3) {

        } else if (preScore == -3) {

        } else {
            preScore = NumberUtils.numformat(preScore);
        }
        req.put("score", String.valueOf(preScore));
        Call<Result> call = NetWorkManager.getRequest().setScore(req);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                System.out.println("成功");
                TTSManager.getInstance().speakText(mExamStu.getStuName() + ",第" + nowCount + "次," + getScoreText(NumberUtils.numformat2(preScore)));

                QMUITipDialog tipDialog2 = new QMUITipDialog.Builder(UpdateScoreZxActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                        .setTipWord("操作成功!")
                        .create();
                if (nowCount == 1) {
                    if (subId == 2) {
                        mExamStu.setJumpScore1(preScore + "");
                    } else if (subId == 3) {
                        mExamStu.setShotScore1(preScore + "");
                    } else {
                        mExamStu.setSpecialScore1(preScore + "");
                    }
                } else if (nowCount == 2) {
                    if (subId == 2) {
                        mExamStu.setJumpScore2(preScore + "");
                    } else if (subId == 3) {
                        mExamStu.setShotScore2(preScore + "");
                    } else {
                        mExamStu.setSpecialScore2(preScore + "");
                    }
                } else if (nowCount == 3) {
                    if (subId == 2) {
                        mExamStu.setJumpScore3(preScore + "");
                    } else if (subId == 3) {
                        mExamStu.setShotScore3(preScore + "");
                    } else {
                        mExamStu.setSpecialScore3(preScore + "");
                    }
                }
                FieldShowRes fieldShowRes = new FieldShowRes();
                fieldShowRes.setType(2);
                fieldShowRes.setStuName(mExamStu.getStuName());
                fieldShowRes.setCount(nowCount);
                fieldShowRes.setDw("");


                if (subId == 2) {
                    fieldShowRes.setZb(Math.toIntExact(mExamStu.getJumpGroup()));
                    fieldShowRes.setXh(Math.toIntExact(mExamStu.getJumpBh()));

                    fieldShowRes.setCj1(mExamStu.getJumpScore1());
                    fieldShowRes.setCj2(mExamStu.getJumpScore2());
                    fieldShowRes.setCj3(mExamStu.getJumpScore3());

                    fieldShowRes.setCj(getMaxOfThreeNumbers(mExamStu.getJumpScore1(), mExamStu.getJumpScore2(), mExamStu.getJumpScore3()));
                } else if (subId == 3) {
                    fieldShowRes.setZb(Math.toIntExact(mExamStu.getShotGroup()));
                    fieldShowRes.setXh(Math.toIntExact(mExamStu.getShotBh()));
                    fieldShowRes.setCj1(mExamStu.getShotScore1());
                    fieldShowRes.setCj2(mExamStu.getShotScore2());
                    fieldShowRes.setCj3(mExamStu.getShotScore3());

                    fieldShowRes.setCj(getMaxOfThreeNumbers(mExamStu.getShotScore1(), mExamStu.getShotScore2(), mExamStu.getShotScore3()));

                } else if (subId > 3) {
                    fieldShowRes.setZb(Math.toIntExact(mExamStu.getSpecialGroup()));
                    fieldShowRes.setXh(Math.toIntExact(mExamStu.getSpecialBh()));
                    fieldShowRes.setCj(mExamStu.getSpecialScore());
                    fieldShowRes.setCj1(mExamStu.getSpecialScore1());
                    fieldShowRes.setCj2(mExamStu.getSpecialScore2());
                    fieldShowRes.setCj3(mExamStu.getSpecialScore3());

                    fieldShowRes.setCj(getMaxOfThreeNumbers(mExamStu.getSpecialScore1(), mExamStu.getSpecialScore2(), mExamStu.getSpecialScore3()));

                }
                fieldShowRes.setCj(getScoreText2(fieldShowRes.getCj()));
                fieldShowRes.setCj1(getScoreText2(fieldShowRes.getCj1()));
                fieldShowRes.setCj2(getScoreText2(fieldShowRes.getCj2()));
                fieldShowRes.setCj3(getScoreText2(fieldShowRes.getCj3()));
                webServer.sendLedInfo(fieldShowRes);

                if (nowCount == 3) {
                    mExamStu = null;
                } else {
                    nextCount();
                }

                showStuInfo();
                runOnUiThread(() -> {
                    checkStuItemAdapter.notifyDataSetChanged();
                    tipDialog.dismiss();
                    preScore = null;
                    surveyResult.setText("-.---米");
                    tipDialog2.show();
                    startSurvey.postDelayed(() -> {
                        tipDialog2.dismiss();
                    }, 500);

                });
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });

//        Call<Result<ExamStuWithScore>> call = NetWorkManager.getRequest().updateScore(req);
//        call.enqueue(new Callback<Result<ExamStuWithScore>>() {
//            @Override
//            public void onResponse(Call<Result<ExamStuWithScore>> call, Response<Result<ExamStuWithScore>> response) {
//                System.out.println("成功");
//                TTSManager.getInstance().speakText(mExamStu.getXm() + ",第" + nowCount + "次," + getScoreText(preScore));
//
//                QMUITipDialog tipDialog2 = new QMUITipDialog.Builder(UpdateScoreActivity.this).setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS).setTipWord("操作成功!").create();
//                if (nowCount == 1) {
//                    mExamStu.setCj1(req.getRawScore() + "");
//                    System.out.println("preScore:" + preScore+";cloud:" + response.body().getData().getCj1());
//                } else if (nowCount == 2) {
//                    mExamStu.setCj2(req.getRawScore() + "");
//                    System.out.println("preScore:" + preScore+";cloud:" + response.body().getData().getCj2());
//                } else if (nowCount == 3) {
//                    mExamStu.setCj3(req.getRawScore() + "");
//                    System.out.println("preScore:" + preScore+";cloud:" + response.body().getData().getCj3());
//                }
//                mExamStu = null;
//                showStuInfo();
//                runOnUiThread(() -> {
//                    checkStuItemAdapter.notifyDataSetChanged();
//                    tipDialog.dismiss();
//                    preScore = null;
//                    surveyResult.setText("-.---米");
//                    tipDialog2.show();
//                    startSurvey.postDelayed(() -> {
//                        tipDialog2.dismiss();
//                    }, 500);
//
//                });
//
//            }
//
//            @Override
//            public void onFailure(Call<Result<ExamStuWithScore>> call, Throwable t) {
//                QMUITipDialog tipDialog2 = new QMUITipDialog.Builder(UpdateScoreActivity.this).setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS).setTipWord("上传失败!").create();
//                TTSManager.getInstance().speakText(mExamStu.getXm() + ",第" + nowCount + "次," + getScoreText(preScore));
//                runOnUiThread(() -> {
//                    tipDialog2.show();
//                    startSurvey.postDelayed(() -> {
//                        tipDialog.dismiss();
//                        tipDialog2.dismiss();
//                    }, 500);
//
//                });
//            }
//        });

//        if (subId == 2) {
//            call = NetWorkManager.getRequest().updateLong(preScore, mExamStu.getExamNum(), nowCount);
//        }
//        if (subId == 3) {
//            call = NetWorkManager.getRequest().updateThrow(preScore, mExamStu.getExamNum(), nowCount);
//        } else if (subId > 3) {
//            call = NetWorkManager.getRequest().updateScoreByKh(preScore, mExamStu.getExamNum(), String.valueOf(subId), nowCount,true);
//
//        }
//        call.enqueue(new Callback<State>() {
//            @Override
//            public void onResponse(Call<State> call, Response<State> response) {

//            }
//
//            @Override
//            public void onFailure(Call<State> call, Throwable t) {
//
//            }
//        });
    }

    public static String getMaxOfThreeNumbers(String num1, String num2, String num3) {
        try {
            double n1 = 0;
            try {
                if (num1 != null && !num1.equals("")) {
                    n1 = Double.parseDouble(num1);
                }
            } catch (Exception e) {

            }
            double n2 = 0;
            try {
                if (num2 != null && !num2.equals("")) {
                    n2 = Double.parseDouble(num2);
                }
            } catch (Exception e) {

            }
            double n3 = 0;
            try {
                if (num3 != null && !num3.equals("")) {
                    n3 = Double.parseDouble(num1);
                }
            } catch (Exception e) {

            }
            double max = Math.max(n1, Math.max(n2, n3));

            // 返回原始字符串形式的最大值
            if (max == n1) return num1;
            if (max == n2) return num2;
            return num3;
        } catch (NumberFormatException e) {
            return "";
        }
    }

    public String getScoreText(double score) {
        if (score == -1) {
            return "违例";
        } else if (score == -2) {
            return "缺考";
        } else if (score == -3) {
            return "伤退";
        } else if (score == -4) {
            return "免考";
        } else {
            return score + "米";
        }
    }

    public String getScoreText(String scoreStr) {
        if (scoreStr == null || scoreStr.equals("")) {
            return "-.---米";
        }
        double score = Double.parseDouble(scoreStr);
        if (score == -1) {
            return "违例";
        } else if (score == -2) {
            return "缺考";
        } else if (score == -3) {
            return "伤退";
        } else if (score == -4) {
            return "免考";
        } else {
            return score + "米";
        }
    }

    public String getScoreText2(String scoreStr) {
        if (scoreStr == null || scoreStr.equals("")) {
            return "-.---米";
        }
        double score = Double.parseDouble(scoreStr);
        score = NumberUtils.numformat2(score);
        if (score == -1) {
            return "违例";
        } else if (score == -2) {
            return "缺考";
        } else if (score == -3) {
            return "伤退";
        } else if (score == -4) {
            return "免考";
        } else {
            return NumberUtils.numformat2(score) + "米";
        }
    }

    class CheckStuItemAdapter extends ArrayAdapter<ExamStu> {
        public CheckStuItemAdapter(@NonNull Context context, int resource, @NonNull List<ExamStu> objects) {
            super(context, resource, objects);
        }


        //每个子项被滚动到屏幕内的时候会被调用
        @SuppressLint("SetTextI18n")
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ExamStu examStuBean = getItem(position);//得到当前项的 Fruit 实例
            //为每一个子项加载设定的布局
            @SuppressLint("ViewHolder")
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_update_stulist, parent, false);
            //分别获取 image view 和 textview 的实例
            if (mExamStu != null && examStuBean.getId() == mExamStu.getId()) {
                view.setBackground(getResources().getDrawable(R.drawable.shape_corner_all_tag));
            } else {
                view.setBackground(getResources().getDrawable(R.drawable.shape_corner_all_white));
            }
            ImageView photo = view.findViewById(R.id.photo);
            TextView no = view.findViewById(R.id.no);
            TextView name = view.findViewById(R.id.name);
            ImageView star1 = view.findViewById(R.id.star1);
            ImageView star2 = view.findViewById(R.id.star2);
            ImageView star3 = view.findViewById(R.id.star3);
            star1.setVisibility(View.INVISIBLE);
            star2.setVisibility(View.INVISIBLE);
            star3.setVisibility(View.INVISIBLE);
            if (subId == 2) {
                if (examStuBean.getJumpScore1() != null && !examStuBean.getJumpScore1().equals("")) {
                    star1.setVisibility(View.VISIBLE);
                }
                if (examStuBean.getJumpScore2() != null && !examStuBean.getJumpScore2().equals("")) {
                    star2.setVisibility(View.VISIBLE);
                }
                if (examStuBean.getJumpScore3() != null && !examStuBean.getJumpScore3().equals("")) {
                    star3.setVisibility(View.VISIBLE);
                }
            } else if (subId == 3) {
                if (examStuBean.getShotScore1() != null && !examStuBean.getShotScore1().equals("")) {
                    star1.setVisibility(View.VISIBLE);
                }
                if (examStuBean.getShotScore2() != null && !examStuBean.getShotScore2().equals("")) {
                    star2.setVisibility(View.VISIBLE);
                }
                if (examStuBean.getShotScore3() != null && !examStuBean.getShotScore3().equals("")) {
                    star3.setVisibility(View.VISIBLE);
                }
            } else {
                if (examStuBean.getSpecialScore1() != null && !examStuBean.getSpecialScore1().equals("")) {
                    star1.setVisibility(View.VISIBLE);
                }
                if (examStuBean.getSpecialScore2() != null && !examStuBean.getSpecialScore2().equals("")) {
                    star2.setVisibility(View.VISIBLE);
                }
                if (examStuBean.getSpecialScore3() != null && !examStuBean.getSpecialScore3().equals("")) {
                    star3.setVisibility(View.VISIBLE);
                }
            }

            name.setText(examStuBean.getStuName() + "");

            if (subId == 2) {
                no.setText(examStuBean.getJumpBh() + "");
            } else if (subId == 3) {
                no.setText(examStuBean.getShotBh() + "");
            } else if (subId > 3) {
                no.setText(examStuBean.getSpecialBh() + "");
            }

            new Thread(() -> {
                Bitmap bitmap = BitmapUtils.loadBitmapWithOkHttp(ConfigManager.getInstance().getIpAddress() + examStuBean.getPhoto());

                if (bitmap != null) {
                    runOnUiThread(() -> {
                        photo.setImageBitmap(bitmap);
                    });
                } else {
                    if (examStuBean.getSex() == null || examStuBean.getSex() == 1) {
                        runOnUiThread(() -> {
                            photo.setImageResource(R.mipmap.boy);
                        });
                    } else {
                        runOnUiThread(() -> {
                            photo.setImageResource(R.mipmap.girl);
                        });
                    }

                }
            }).start();
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectStu(examStuBean);
                }
            });
            return view;
        }
    }

    void selectStu(ExamStu examStu) {
        mExamStu = examStu;
        showStuInfo();
    }

    int NowIndex = 0;

    double boyMax = 9.20;
    double girlMax = 7.80;

    double boyQqMax = 12;
    double girlQqMax = 9.6;

    @SuppressLint("SetTextI18n")
    void showStuInfo() {
        runOnUiThread(() -> {
            checkStuItemAdapter.notifyDataSetChanged();
            if (mExamStu != null) {
                for (int i = 0; i < examStuBeanArrayList.size(); i++) {
                    if (Objects.equals(examStuBeanArrayList.get(i).getId(), mExamStu.getId())) {
                        NowIndex = i;
                    }
                }


                int middle = checkStuListView.getHeight() / 2; // 计算列表中间的位置
                if (NowIndex != 0) {
                    checkStuListView.setSelectionFromTop(NowIndex - 1, middle - (int) (middle / 3.0));
                } else {
                    checkStuListView.setSelectionFromTop(0, middle - (int) (middle / 3.0));
                }

                stuName.setText(mExamStu.getStuName());
                stuKsh.setText(mExamStu.getExamNum() + "");
                if (subId == 2) {
                    groupXhText.setText(mExamStu.getJumpBh() + "");
                    groupIdText.setText(mExamStu.getJumpGroup() + "");
                } else if (subId == 3) {
                    groupXhText.setText(mExamStu.getShotBh() + "");
                    groupIdText.setText(mExamStu.getShotGroup() + "");
                } else if (subId > 3) {
                    groupXhText.setText(mExamStu.getSpecialBh() + "");
                    groupIdText.setText(mExamStu.getSpecialGroup() + "");
                }

                stuInfoLayout.setVisibility(View.VISIBLE);
                noStuContent.setVisibility(View.GONE);
                stuResult.setText("-.---" + "米");
                FieldShowRes fieldShowRes = new FieldShowRes();
                fieldShowRes.setType(1);
                fieldShowRes.setStuName(mExamStu.getStuName());
                fieldShowRes.setCount(nowCount);
                fieldShowRes.setDw("");


                if (subId == 2) {
                    groupXhText.setText(mExamStu.getJumpBh() + "");
                    groupIdText.setText(mExamStu.getJumpGroup() + "");
                    fieldShowRes.setZb(Math.toIntExact(mExamStu.getJumpGroup()));
                    fieldShowRes.setXh(Math.toIntExact(mExamStu.getJumpBh()));
                } else if (subId == 3) {
                    groupXhText.setText(mExamStu.getShotBh() + "");
                    groupIdText.setText(mExamStu.getShotGroup() + "");
                    fieldShowRes.setZb(Math.toIntExact(mExamStu.getShotGroup()));
                    fieldShowRes.setXh(Math.toIntExact(mExamStu.getShotBh()));
                } else if (subId > 3) {
                    groupXhText.setText(mExamStu.getSpecialBh() + "");
                    groupIdText.setText(mExamStu.getSpecialGroup() + "");
                    fieldShowRes.setZb(Math.toIntExact(mExamStu.getSpecialGroup()));
                    fieldShowRes.setXh(Math.toIntExact(mExamStu.getSpecialBh()));
                }

                webServer.sendLedInfo(fieldShowRes);
                new Thread(() -> {
                    Bitmap bitmap = bitmapMap.get(mExamStu.getExamNum());
                    if (bitmap == null) {
                        if (mExamStu.getPhoto() != null && !mExamStu.getPhoto().trim().equals("")) {
                            bitmap = BitmapUtils.loadBitmapWithOkHttp(ConfigManager.getInstance().getIpAddress() + mExamStu.getPhoto());
                            bitmap = BitmapUtils.calculateInSampleSize(bitmap, 100, 100);
                        }
                    }
                    if (bitmap == null) {
                        if (mExamStu.getSex() == null || (mExamStu.getSex() != null && mExamStu.getSex().equals(1))) {
                            Resources res = getResources();
                            bitmap = BitmapFactory.decodeResource(res, R.drawable.boy);

                        } else if (mExamStu.getSex() != null && mExamStu.getSex().equals(2)) {
                            Resources res = getResources();
                            bitmap = BitmapFactory.decodeResource(res, R.drawable.girl);
                        }
                    }
                    Bitmap finalBitmap = bitmap;
                    runOnUiThread(() -> {
                        if (finalBitmap != null) {
                            bitmapMap.put(mExamStu.getExamNum(), finalBitmap);
                            stuImage.setImageBitmap(finalBitmap);
                        }
                    });
                }).start();

                if (nowCount == 1) {
                    if (subId == 2) {
                        stuResult.setText(getScoreText(mExamStu.getJumpScore1()));
                    } else if (subId == 3) {
                        stuResult.setText(getScoreText(mExamStu.getShotScore1()));
                    } else {
                        stuResult.setText(getScoreText(mExamStu.getSpecialScore1()));
                    }
                } else if (nowCount == 2) {
                    if (subId == 2) {
                        stuResult.setText(getScoreText(mExamStu.getJumpScore2()));
                    } else if (subId == 3) {
                        stuResult.setText(getScoreText(mExamStu.getShotScore2()));
                    } else {
                        stuResult.setText(getScoreText(mExamStu.getSpecialScore2()));
                    }
                } else if (nowCount == 3) {
                    if (subId == 2) {
                        stuResult.setText(getScoreText(mExamStu.getJumpScore3()));
                    } else if (subId == 3) {
                        stuResult.setText(getScoreText(mExamStu.getShotScore3()));
                    } else {
                        stuResult.setText(getScoreText(mExamStu.getSpecialScore3()));
                    }
                }

                boolean isQuekao = false;
                if (subId == 2 || subId == 3) {
                    if (subId == 2) {
                        if ((mExamStu.getJumpScore1() != null && Double.parseDouble(mExamStu.getJumpScore1()) == -2) || (mExamStu.getJumpScore2() != null && Double.parseDouble(mExamStu.getJumpScore2()) == -2)) {
                            isQuekao = true;
                        }
                    }
                    if (subId == 3) {
                        if ((mExamStu.getShotScore1() != null && Double.parseDouble(mExamStu.getShotScore1()) == -2) || (mExamStu.getShotScore2() != null && Double.parseDouble(mExamStu.getShotScore2()) == -2)) {
                            isQuekao = true;
                        }
                    }
                }

                if (false) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(UpdateScoreZxActivity.this);
                    builder.setTitle("确认");
                    builder.setMessage("检测到已缺考，是否跳过？");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            nextStu();
                        }
                    });
                    builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });
                    builder.show();
                }

                boolean isManfen = false;
                if (subId == 2 || subId == 3) {
                    if (subId == 2) {
                        if (mExamStu.getSex() == 1) {
                            if ((mExamStu.getJumpScore1() != null && Double.parseDouble(mExamStu.getJumpScore1()) >= boyMax) || (mExamStu.getJumpScore2() != null && Double.parseDouble(mExamStu.getJumpScore2()) >= boyMax)) {
                                isManfen = true;
                            }
                        }
                        if (mExamStu.getSex() == 2) {
                            if ((mExamStu.getJumpScore1() != null && Double.parseDouble(mExamStu.getJumpScore1()) >= girlMax) || (mExamStu.getJumpScore2() != null && Double.parseDouble(mExamStu.getJumpScore2()) >= girlMax)) {
                                isManfen = true;
                            }
                        }
                    }
                    if (subId == 3) {
                        if (mExamStu.getSex() == 1) {
                            if ((mExamStu.getShotScore1() != null && Double.parseDouble(mExamStu.getShotScore1()) >= boyQqMax) || (mExamStu.getShotScore2() != null && Double.parseDouble(mExamStu.getShotScore2()) >= boyQqMax)) {
                                isManfen = true;
                            }
                        }
                        if (mExamStu.getSex() == 2) {
                            if ((mExamStu.getShotScore1() != null && Double.parseDouble(mExamStu.getShotScore1()) >= girlQqMax) || (mExamStu.getShotScore2() != null && Double.parseDouble(mExamStu.getShotScore2()) >= girlQqMax)) {
                                isManfen = true;
                            }
                        }
                    }
                }
                if (false) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(UpdateScoreZxActivity.this);
                    builder.setTitle("确认");
                    builder.setMessage("检测到已满分，是否跳过？");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            nextStu();
                        }
                    });
                    builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });
                    builder.show();
                }
            } else {
                stuResult.setText("-.---" + "米");
                stuInfoLayout.setVisibility(View.GONE);
                noStuContent.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //a==29
//        ToastUtils.toast(getBaseContext(),keyCode+"");
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent home = new Intent(Intent.ACTION_MAIN);
//            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            home.addCategory(Intent.CATEGORY_HOME);
//            startActivity(home);
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_HOME) {
//            Intent home = new Intent(Intent.ACTION_MAIN);
//            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            home.addCategory(Intent.CATEGORY_HOME);
//            startActivity(home);
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME) {
//            Intent home = new Intent(Intent.ACTION_MAIN);
//            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            home.addCategory(Intent.CATEGORY_HOME);
//            startActivity(home);
            return true;
        }

        //22上键
        if (keyCode == 22) {
            uplight.setChecked(TotalStationManager.getInstance().changeLASER_POINTER());
        }

        //22下键
        if (keyCode == 21) {
            downlight.setChecked(TotalStationManager.getInstance().changeLASER_PLUMMET());
        }


        return super.onKeyDown(keyCode, event);
    }

    class RecordAdapter extends ArrayAdapter<LocalRecord> {
        public RecordAdapter(@NonNull Context context, int resource, @NonNull List<LocalRecord> objects) {
            super(context, resource, objects);
        }


        //每个子项被滚动到屏幕内的时候会被调用
        @SuppressLint("SetTextI18n")
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            LocalRecord localRecord = getItem(position);//得到当前项的 Fruit 实例
            //为每一个子项加载设定的布局
            @SuppressLint("ViewHolder")
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_localrecord, parent, false);
            TextView zxmcText = view.findViewById(R.id.zxmcText);
            TextView xmmcText = view.findViewById(R.id.xmmcText);
            TextView nameText = view.findViewById(R.id.nameText);
            TextView scoreText = view.findViewById(R.id.scoreText);
            TextView countText = view.findViewById(R.id.countText);
            TextView timeText = view.findViewById(R.id.timeText);
            zxmcText.setText(localRecord.getZxmc());
            xmmcText.setText(localRecord.getXmmc());
            nameText.setText(localRecord.getName());
            countText.setText(localRecord.getCount() + "");
            scoreText.setText(localRecord.getScore());

            if (localRecord.getDateField() != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedNow = formatter.format(localRecord.getDateField());
                timeText.setText(formattedNow);
            }
            view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    runOnUiThread(() -> {
                        preScore = Double.parseDouble(localRecord.getScore());
                        surveyResult.setText(getScoreText(preScore));
                        historyLayout.setVisibility(View.GONE);
                    });
                    return false;
                }
            });

            return view;
        }
    }

}
